<?php
namespace controller;

class AddressController extends BaseController
{
    /**
     * Retrieve one or more records and output as JSON
     * @param integer $id
     * @return string
     */
    public function executeGet($id)
    {
        $this->sendJsonHeaders();
              
        if ($id) { // output one specific record
            $data = \model\Address::getAddressById($id);
        } else { // output all data; TODO: pagination
            $data = \model\Address::getAddresses();
        }
        if (is_array($data)) {
            $json = json_encode($data);
            return $json;
        } else {
            return $this->execute404();
        }
    }

    /**
     * Create a new record
     * @param Array $parameters
     * @return string
     */
    public function executeCreate($parameters)
    {
        $data = \model\Address::addAddress($parameters);
        if (is_array($data)) {
            $this->sendSuccessHeaders();
            $json = json_encode($data);
            return $json;
        } else {
            $this->sendErrorHeaders();
            return "ERROR";
        }
    }

    /**
     * Update an existing record
     * @param Integer $id
     * @param Array $parameters
     * @return string
     */
    public function executeUpdate($id, $parameters)
    {
        \model\Address::updateAddress($id, $parameters);
        $this->sendSuccessHeaders();
        $data = \model\Address::getAddressById($id);
        $json = json_encode($data);
        return $json;
    }

    /**
     * Delete record
     * @param Integer $id
     * @return string
     */
    public function executeDelete($id)
    {
        $success = \model\Address::deleteAddress($id);
        if ($success) {
            $this->sendSuccessHeaders();
            return "OK";
        } else {
            return $this->execute404();
        }
    }
}
